import RoleDataScope from '../consts/roleDataScope';
import knex from '../utils/knex';
import logger from '../utils/logger';

/**
 * 查询当前用户的权限
 */
export const getPermissions = async function (userId: number) {
    // 查询当前用户的所有菜单集合，包括按钮url
    const menus = await knex({ m: 'sys_menu' })
        .leftJoin({ rm: 'sys_role_menu' }, 'm.id', 'rm.menu_id')
        .leftJoin({ r: 'sys_role' }, 'r.id', 'rm.role_id')
        .leftJoin({ ur: 'sys_user_role' }, 'ur.role_id', 'r.id')
        .columns('m.*')
        .where({ 'ur.user_id': userId, 'm.status': 0, 'm.type': 2 })
        .orderBy('m.sort_num', 'asc')
        .select();

    logger.info('开始授权。。。');
    const urls = menus
        .filter((item) => item.type === 2 && item.permission != null && item.permission !== '')
        .map((item) => {
            return item.permission;
        });
    logger.info('用户所有接口url', urls);
    logger.info('授权结束。。。');

    return urls;
};

/**
 * 数据权限处理器
 * @param userAlias
 * @param orgAlias
 * @returns
 */
export const dataScopeHandler = async function (userId: number, userAlias?: string, orgAlias: string = 'o') {
    // 获取当前用户的部门id
    const { org_id: orgId } = await knex('sys_user').where({ id: userId }).first('org_id');
    // 获取当前用户所在部门的子部门的id
    const orgPids = await knex('sys_org').where({ pid: orgId }).select('id');

    // 当前部门及子部门id
    const tmp = [orgId, ...orgPids.map((org) => org.id)];
    const orgAndPorgIds = tmp.toString();

    /**
     * select r.* from role r
     * left join sys_user_role ur on ur.role_id = r.id,
     * left join sys_user u on u.id = ur.user_id
     * where u.id = ?
     */
    const roles = await knex({ r: 'sys_role' })
        .leftJoin({ ur: 'sys_user_role' }, 'ur.role_id', 'r.id')
        .leftJoin({ u: 'sys_user' }, 'ur.user_id', 'u.id')
        .where({ 'u.id': userId })
        .columns('r.*')
        .select();

    // 取最小的数据权限
    const dsTypes = roles.map((item) => item.ds_type);
    const dsType = Math.min.apply(null, dsTypes);

    // 获取按明细设置机构id，用逗号分隔
    let dsScopes = '';
    for (const role of roles) {
        if (!role.ds_scope) {
            continue;
        }
        dsScopes += role.ds_scope + ',';
    }
    if (dsScopes.length > 0) {
        dsScopes = dsScopes.substr(0, dsScopes.length - 1);
    }

    let sqlWhere = '';

    switch (dsType) {
        // 1.全部数据
        case RoleDataScope.ALL:
            break;
        // 2.按明细设置
        case RoleDataScope.Custom:
            sqlWhere += `${orgAlias}.id in (${dsScopes})`;
            break;
        // 3.所在公司（部门）及以下数据
        case RoleDataScope.DepartmentBelow:
            sqlWhere += `${orgAlias}.id in (${orgAndPorgIds})`;
            break;
        // 4.所在公司（部门）数据
        case RoleDataScope.Department:
            sqlWhere += `${orgAlias}.id = ${orgId}`;
            break;
        // 5.仅本人数据
        case RoleDataScope.Self:
            if (userAlias) {
                sqlWhere += `${userAlias}.id = ${userId}`;
            } else {
                sqlWhere += `1=0`;
            }
            break;
        default:
            break;
    }

    return sqlWhere;
};
